#
#INJECT BY REGEX
#PMOD PLUGIN
#

import re, urllib, htmlentitydefs
from urlparse import parse_qs

name = "Inject By Regex" #Name
web = "ibr.html"         #Web Page File

def setup(storage): 
    storage.regex = ""
    storage.repl = ""

def edit_REQUEST(request,storage):
    return None

def edit_RESPONSE(response,storage):
    if storage.enabled:
        if("content-type" in response.headers.keys() and storage.regex != ""):
            if('text/html' in response.headers.getList("content-type")[0]):
                response.body = re.sub(storage.regex,storage.repl,response.body)
                #response.body = re.sub("</html>","<div style='position:fixed;left:0px;top:0px;width:100%;background-color:white;'><center><img src='http://lostboy.net/wp-content/uploads/2009/05/defcon.png'></center></div></html>",response.body)

def do_PAGE(storage):
    out = ""
    if(storage.enabled):
        out+="<a href='ibr.html?disable'>Disable</a><br><br>"+urllib.quote(storage.regex)+"<br>"+urllib.quote(storage.repl)+"<br><br>SETUP:<br><form action='ibr.html'>Regex to find: <input type=text name=regex></br>Regex/text to replace with: <input type=text name=repl><br><input type=submit value='Update' name=update></form>"
    else:
        out+="<a href='ibr.html?enable'>Enable</a>"
    return out

def handle_HTTP_RESPONSE(response,storage):
    if response.path.find("?") >= 0: #Probably editing something...
        query = response.path[response.path.find("?")+1:]
        if query=="enable":
            storage.enabled = 1
        if query=="disable":
            storage.enabled = 0
        if "update=Update" in query: #Update
            q = parse_qs(query)
            if 'regex' in q:
                storage.regex = q["regex"][0]
            if 'repl' in q:
                storage.repl = q["repl"][0]

